#include "visul_communicate.h"

extern UART_HandleTypeDef huart2;
extern DMA_HandleTypeDef hdma_usart2_rx;
extern TIM_HandleTypeDef htim5;
uint8_t huart2_rev_data[100] = {0};
uint8_t send_master_data_pack[5] = {0};
uint32_t ctr_value_u32 = 0;
float ctr_value_flo = 0;
float ctr_value_flo_L = 0;
float targer_circle = 0;
uint8_t Ctr_high_M_flag = 0;
uint32_t debug_test_count = 0;

void visual_communicate_init(void)
{
    __HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
    Tovisual_dataPack();
    __HAL_UART_ENABLE_IT(&huart2, UART_FLAG_IDLE);
    HAL_UART_Receive_DMA(&huart2, huart2_rev_data, sizeof(huart2_rev_data));

    HAL_TIM_Base_Start_IT(&htim5);
}


void visual_data_deal(uint8_t rev_len)
{
    if(huart2_rev_data[0] == 0xAA && huart2_rev_data[rev_len - 1] == 0x55)
    {
      //发送端是先低位 后高位 所以解析遵循这种的逻辑
      ctr_value_u32 = huart2_rev_data[1] | (huart2_rev_data[2] << 8) | (huart2_rev_data[3] << 16) | (huart2_rev_data[4] << 24);
      ctr_value_flo_L = ctr_value_flo;
      ctr_value_flo = *(float *)(&ctr_value_u32);
      if(ctr_value_flo == ctr_value_flo_L) Ctr_high_M_flag = 0; //两次相同数据 即舍弃
      else Ctr_high_M_flag = 1;
      debug_test_count ++;
    } 
}


void rev_visul_data_analysis(void)
{
    int32_t read_temp = 0;
    int16_t rev_data_length_temp = 0;
    if(__HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE) != RESET)
    {
        __HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_IDLE);
        HAL_UART_DMAStop(&huart2); 
        read_temp = (&huart2)->Instance->SR;
        read_temp = (&huart2)->Instance->DR;
        rev_data_length_temp = sizeof(huart2_rev_data) - (&hdma_usart2_rx)->Instance->NDTR;
        visual_data_deal(rev_data_length_temp);
        memset(huart2_rev_data, sizeof(huart2_rev_data), 0);
        HAL_UART_Receive_DMA(&huart2, huart2_rev_data, sizeof(huart2_rev_data));
    }
}

void Tovisual_dataPack(void)
{
    uint8_t index = 0;

    send_master_data_pack[index ++] = 0x66;
    HAL_UART_Transmit_DMA(&huart2, send_master_data_pack, index);
}


